import { useState } from 'react';
import Sform from './src/form';
import { Button, message, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import TableAction, {
  MenuItem,
} from '@/components/commonComponent/tableAction/tableAction';
import APDrawer from './src/drawer';
import { useAPDrawer } from '@/hooks/baseHook';
import useRequest from '@ahooksjs/use-request';
import { getAlgorithms } from '@/api/sr-stms';
import { splitSearchParams } from '@/utils/common';
import { delete_algorithm_name_api } from '@/api/sr-stms';

const CommodityCategory = () => {
  const { handleAddClick, handleClose, handleEditClick, record, visible } =
    useAPDrawer<any>();
  const [searchParams, setSearchParams] = useState<SearchParam[]>([]);
  const { tableProps, refresh } = useRequest(
    ({ current, pageSize }) =>
      getAlgorithms({
        page: current,
        size: pageSize,
        search_params: searchParams,
      }),
    {
      paginated: true,
      refreshDeps: [searchParams],
      formatResult: (res) => ({
        list: res.data.list,
        total: res.data.total_elements,
      }),
    },
  );

  const columns: ColumnsType<any> = [
    // { title: '编码', dataIndex: 'id' },
    { title: '模型标识', dataIndex: 'algorithm_name' },
    { title: '项目名称', dataIndex: 'project_name' },
    { title: '模型类型', dataIndex: 'model_label' },
    { title: '模型名称', dataIndex: 'model_name' },
    {title: '备注', dataIndex: 'note'},
    {
      title: '操作',
      render: (text, record) => {
        return (
          <TableAction
            record={record}
            menuList={menuList}
            onEditClick={handleEditClick}
          ></TableAction>
        );
      },
    },
  ];

  const menuList: MenuItem<any>[] = [
    { name: '删除', fn: (record) => handleDelClick(record.algorithm_name) },
  ];

  const handleDelClick = async (algorithm_name: string) => {
    //调用删除接口
    await delete_algorithm_name_api(algorithm_name)();
    message.success('删除成功！');
    refresh();
  };

  /** 表单查询回调 */
  const formSearch = (vals: any) => {
    setSearchParams(splitSearchParams(vals));
  };

  /** 新增、编辑成功回调 */
  const drawerCallback = () => {
    refresh();
  };

  return (
    <div style={{ padding: 20, background: '#fff' }}>
      <APDrawer
        visible={visible}
        record={record}
        onClose={handleClose}
        callback={drawerCallback}
      ></APDrawer>
      <Sform formSearch={formSearch}></Sform>
      <div style={{ marginBottom: 15 }}>
        <Button type="primary" onClick={handleAddClick}>
          新增
        </Button>
      </div>
      <Table
        {...tableProps}
        pagination={{
          ...tableProps.pagination,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `总共 ${total} 条`,
        }}
        columns={columns}
        rowKey={(record) => record.id}
        bordered
      ></Table>
    </div>
  );
};

export default CommodityCategory;
